import os, sys
import subprocess
from subprocess import Popen
import re

class StatReader:
    
    def __init__(self, hostname, length):
        self.hostname = hostname
        self.length = length
        self.reg = re.compile(r"\S+:\s+\S+\s+(\d+.\d+)\s+\d+.\d+\s+(\d+.\d+)\s+\d+.\d+\s+\d+.\d+\s+\d+.\d+\s+\d+.\d+\s+(\d+.\d+)\s+\d+.\d+")
        self.user = 0
        self.sys = 0
        self.idle = 0
        self.process = None

    def start(self):
        self.process = Popen(["ssh", self.hostname, "mpstat", "1", "%d"%self.length], stdout=subprocess.PIPE)

    def end(self):
        self.process.wait()
        strings = self.process.stdout.readlines()
        found = ""
        for string in strings:
            if string.find("Average") >= 0:
                found = string
        ret = self.reg.search(found)
        self.user = float(ret.group(1))
        self.sys = float(ret.group(2))
        self.idle = float(ret.group(3))
    
    def print_results(self):
        print "%.02f\t%.02f\t%.02f"%(self.user, self.sys, self.idle)
        

    def get_results(self):
        return (self.user, self.sys, self.idle)

class StatPrint:
    
    def __init__(self, filename):
        self.outfile = open(filename, 'w')

    def print_util(self, load, vals):
        (user, sys, idle) = vals
        self.outfile.write("%d\t%.02f\t%.02f\t%.02f\n"%(load, user, sys, idle))
        self.outfile.flush()



if __name__ == '__main__' :

    process = Popen(["mpstat", "1", "10"], stdout=subprocess.PIPE)
    process.wait()
    strings = process.stdout.readlines()
    found = ""
    for string in strings:
        if string.find("Average") >= 0:
            print string
            found = string
    reg = re.compile(r"\S+:\s+\S+\s+(\d+.\d+)\s+\d+.\d+\s+(\d+.\d+)\s+\d+.\d+\s+\d+.\d+\s+\d+.\d+\s+\d+.\d+\s+(\d+.\d+)\s+\d+.\d+")
    ret = reg.search(string)
    user = float(ret.group(1))
    sys = float(ret.group(2))
    idle = float(ret.group(3))
    print "%.02f\t%.02f\t%.02f"%(user, sys, idle)
    
